(function () {
    let filenames=[]
    let files=[];
    let imageFilenames=[]
    let imageFiles=[];
    document.getElementById("files").addEventListener('change', function (event) {
        filenames=[]
        files=[];
        for(var i=0; i<event.target.files.length; i++) {
            filenames.push(event.target.files[i].name)
            files.push(event.target.files[i])
        }
    });
    document.getElementById("coverImage").addEventListener('change', function (event) {
        imageFilenames=[]
        imageFiles=[];
        for(var i=0; i<event.target.files.length; i++) {
            imageFilenames.push(event.target.files[i].name)
            imageFiles.push(event.target.files[i])
        }
    });
    $("#submit").click(function () {
        let title=$("#title").val()
        let description=$("#description").val()
        let fileName=filenames[0]
        let tags=$("#tags").val()
        let category=0
        let number=Number($("#number").val())
        let total=$("#total").val()
        let permission=$("#permission").val()
        let imageExt=$("#imageExt").val()

        /**
         * 判断标题
         */
        if (title.length==0){
            alert("请输入影片标题")
            return
        }

        /**
         * 判断集数
         */
        if (isNaN(number)&&total==undefined){
            number=1
            total=1
        }else {
            if (isNaN(number)||isNaN(total)){
                alert("请输入正确的集数")
                return
            }else {
                total=Number(total)
                category=1
            }
            if (number>total){
                alert("当前集数大于全剧集数，请重新输入")
                return
            }
        }

        /**
         * 判断影片
         */
        if (files.length==0){
            alert("请选择影片")
            return
        }else {
            if (filenames[0].endsWith("3gp")||filenames[0].endsWith("avi")||filenames[0].endsWith("flv")||
                filenames[0].endsWith("gif")||filenames[0].endsWith("m3u8")||filenames[0].endsWith("mov")
                ||filenames[0].endsWith("mp4")
                ||filenames[0].endsWith("qt")) {
            }else {
                alert("影片格式不正确，请重新选择")
                return
            }
        }

        /**
         * 判断封面图片
         */
        if (imageFiles.length==0){

        }else {
            if (imageFilenames[0].endsWith("png") || imageFilenames[0].endsWith("jpg") || imageFilenames[0].endsWith("jpeg")) {
            }else {
                alert("封面图片格式不正确")
                return
            }

        }

        /**
         * 获取上传凭证和上传地址（包括封面图片）
         */
        $.ajax({
            type:"POST",
            url:"/video/video_upload",
            data:{
                title,
                description,
                fileName,
                tags,
                category,
                permission,
                imageExt,
                total,
                number
            },
            dataType:"json",
            success:function (data,status) {
                console.log(data);
                if (data==null){
                    alert("请检查文件或者视频标签是否正确")
                }
                let uploadauth=data.uploadAuth
                let uploadAddress=data.uploadAddress
                let id=data.aid

                let imguploadauth=data.coverImage.uploadAuth
                let imguploadAddress=data.coverImage.uploadAddress
                let imgid=data.coverImage.imageId

                let uploader = new AliyunUpload.Vod({
                    partSize: 1048576,
                    parallel: 5,
                    retryCount: 3,
                    retryDuration: 2,
                    'onUploadstarted': function (uploadInfo) {
                        console.log(uploadInfo.videoId+"onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                        uploader.setUploadAuthAndAddress(uploadInfo,uploadauth,/*上传凭证*/
                            uploadAddress,/*上传地址*/
                            id);/*id*/
                        let $process=$('<div class="input-group col-md-offset-3 col-md-6"><span class="input-group-addon">上传进度：</span> <input class="form-control" type="text" placeholder="上传进度" id="'+id+'"  readOnly></div>')
                        $("#upform").append($process)
                    },
                    // 文件上传成功
                    'onUploadSucceed': function (uploadInfo) {
                        console.log('文件上传成功');
                        if (uploadInfo.videoId==id) {
                            $("#"+id).parent().remove()
                        }
                        if (uploadInfo.videoId==imgid) {
                            $("#"+imgid).parent().remove()
                        }
                        // console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                    },
                    // 文件上传失败
                    'onUploadFailed': function (uploadInfo, code, message) {
                        console.log("文件上传失败");
                        if (uploadInfo.videoId==id) {
                            $("#"+id).val("上传失败")
                        }
                        if (uploadInfo.videoId==imgid) {
                            $("#"+imgid).val("上传失败")
                        }
                        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
                    },
                    // 文件上传进度，单位：字节
                    'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                        console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
                        console.log(uploadInfo);
                        if (uploadInfo.videoId==id) {
                            $("#"+id).val(uploadInfo.file.name+":     "+Math.ceil(loadedPercent * 100) + "%")
                        }
                        if (uploadInfo.videoId==imgid) {
                            $("#"+imgid).val(uploadInfo.file.name+":     "+Math.ceil(loadedPercent * 100) + "%")
                        }
                    },
                    // 上传凭证超时
                    'onUploadTokenExpired': function (uploadInfo) {
                        console.log("上传凭证超时");
                        // uploader.resumeUploadWithAuth(uploadAuth);
                    },
                    //全部文件上传结束
                    'onUploadEnd':function(uploadInfo){
                        console.log("全部文件上传结束");
                    }
                });
                for (let i=0;i<files.length;i++) {
                    uploader.addFile(files[i], null, null, null, null);
                }
                uploader.startUpload();

                let imageUploader = new AliyunUpload.Vod({
                    partSize: 1048576,
                    parallel: 5,
                    retryCount: 3,
                    retryDuration: 2,
                    'onUploadstarted': function (uploadInfo) {
                        console.log(uploadInfo.videoId+"onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                        //上传方式1, 需要根据uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress，如果videoId有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
                        uploader.setUploadAuthAndAddress(uploadInfo,imguploadauth,/*上传凭证*/
                            imguploadAddress,/*上传地址*/
                            imgid);/*id*/
                        let $process=$('<div class="input-group col-md-offset-3 col-md-6"><span class="input-group-addon">上传进度：</span> <input class="form-control" type="text" placeholder="上传进度" id="'+imgid+'"  readOnly></div>')
                        $("#upform").append($process)
                    },
                    // 文件上传成功
                    'onUploadSucceed': function (uploadInfo) {
                        console.log('文件上传成功img');
                        // console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                    },
                    // 文件上传失败
                    'onUploadFailed': function (uploadInfo, code, message) {

                        console.log("文件上传失败");
                        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
                    },
                    // 文件上传进度，单位：字节
                    'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                        console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
                    },
                    // 上传凭证超时
                    'onUploadTokenExpired': function (uploadInfo) {
                        console.log("上传凭证超时");
                        //上传方式1  实现时，根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
                        // uploader.resumeUploadWithAuth(uploadAuth);
                    },
                    //全部文件上传结束
                    'onUploadEnd':function(uploadInfo){
                        console.log("全部文件上传结束img")
                    }
                });
                for (let i=0;i<imageFiles.length;i++) {
                    imageUploader.addFile(imageFiles[i], null, null, null, null);
                }
                imageUploader.startUpload();
            },
            error:function (data,status) {
                console.log(status);
                /**
                 * 发ajax删除视频
                 */
            }
        })
    })
})()